<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!-- 以逗号分割的产品服务：1-&gt;无忧退货；2-&gt;快速退款；3-&gt;免费包邮 -->
      <el-form-item label="产品服务" prop="serviceIdAll">
        <el-select v-model="serviceIdAll" clearable multiple placeholder="请选择">
          <el-option label="无忧退货" value="1">无忧退货</el-option>
          <el-option label="快速退款" value="2">快速退款</el-option>
          <el-option label="免费包邮" value="3">免费包邮</el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="品牌" clearable prop="brandId">
        <el-select v-model="queryParams.brandId" clearable placeholder="请选择">
          <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">{{
              item.name
            }}
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="地州" clearable prop="regions">
        <el-select v-model="queryParams.regionId" clearable placeholder="请选择">
          <el-option v-for="item in regionList" :key="item.id" :label="item.name" :value="item.id">{{
              item.name
            }}
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['shopping:product:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['shopping:product:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" border>
      <el-table-column label="商品编号" align="center" prop="id"/>
      <el-table-column label="商品名称" align="center" prop="name"/>
      <el-table-column label="商品图片" align="center" prop="defaultImg">
        <template slot-scope="scope">
          <el-image :src="`${scope.row.defaultImg}`" fit="cover" :preview-src-list="[scope.row.defaultImg]"
                    style="width: 50px; height: 50px;"/>
        </template>
      </el-table-column>
      <el-table-column label="无销售价" align="center" prop="price">
        <template slot-scope="scope">
          <span>￥{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存数量" align="center" prop="stock"/>
      <!-- 以逗号分割的产品服务：1-&gt;无忧退货；2-&gt;快速退款；3-&gt;免费包邮 -->
      <el-table-column label="产品服务" align="center" prop="serviceIds">
        <template #default="{ row, $index }">
          <el-row v-for="(serviceId, index) in row.serviceIds.split(',')" :key="index">
            <span style="color: #00afff">
              {{ serviceId == 1 ? '无忧退货' : serviceId == 2 ? '快速退款' : '免费包邮' }}
            </span>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brandName"/>
      <el-table-column label="所属地州" align="center" prop="regionName"/>

      <el-table-column label="SKU库存" align="center">
        <template #default="{ row, $index }">
          <el-button type="primary" icon="el-icon-edit" circle @click="handleSku(row)"></el-button>
        </template>
      </el-table-column>

      <!-- ：0-&gt;未审核；1-&gt;审核通过 -->
      <el-table-column label="审核状态" align="center" prop="verifyStatus">
        <template #default="{ row, $index }">
          <span style="color: #00afff">
            {{ row.verifyStatus == 0 ? '未审核' : '审核通过' }}
          </span>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
                     v-hasPermi="['shopping.productDetail.show']">详细
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['shopping:product:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['shopping:product:remove']">删除
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-check" v-show="scope.row.verifyStatus!=1"
                     @click="updateVerifyStatus(scope.row)"
                     v-hasPermi="['shopping:product:verifyStatus']">审核通过
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>


    <el-dialog
      title="编辑sku"
      :visible.sync="isShowSku"
      width="50%">
      <el-table :data="skuData.tableData" style="width: 100%">
        <el-table-column v-for="column in skuData.columns" :key="column.prop" :label="column.label"
                         :prop="column.prop">
          <template slot-scope="scope">
            <el-input v-model="scope.row[column.prop]" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
    <el-button @click="isShowSku = false">取 消</el-button>
    <el-button type="primary" @click="affrimSubmitUpdateSku"  v-hasPermi="['shopping:product:edit']">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import {listProduct, getProduct, delProduct, addProduct, updateProduct, getSku,updateSku,updateVerifyStatus} from "@/api/shopping/product";
import {getBrandName, getRegionName,getProductNames} from "@/api/common/common";
import item from "@/layout/components/Sidebar/Item";

export default {
  name: "Product",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      skuData: {
        columns: [],
        tableData: [],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brandId: null,
        regionId: null,
        name: null,
        description: null,
        stockQuantity: null,
        defaultImg: null,
        albumPics: null,
        serviceIds: null,
        verifyStatus: null,
        promotionPrice: null,
        stock: null,
        lowStock: null,
        giftPoint: null,
        promotionType: null,
        status: null,
        type:"all"
      },
      //外部存数组
      serviceIdAll: [],
      // 表单参数
      form: {},
      // 商品品牌下拉框数据
      brandList: [],
      // 商品地区下拉框数据
      regionList: [],
      isShowSku: false,
      skuSpDataList: []
    };
  },
  created() {
    this.getList();
    this.getBrandNames()
    this.getRegionNames()

  },
  methods: {
    //审核商品
    updateVerifyStatus(row){
      this.$modal.confirm('确实要审核通过该商品吗？').then(function () {
        return updateVerifyStatus(row.id);
      }).then(() => {
        this.getList()
        this.$message.success("审核通过")
      })
    },
    //确定提交修改sku
    affrimSubmitUpdateSku() {
      console.log(this.skuData)
      let updateSkuList = []
      this.skuSpDataList.forEach((item, index) => {
        updateSkuList.push({
          id: item.id,
          price: this.skuData.tableData[index].salePrice,
          promotionPrice: this.skuData.tableData[index].promotionPrice,
          stock: this.skuData.tableData[index].stock,
          lowStock: this.skuData.tableData[index].warningStock,
          spData: JSON.stringify(this.transformData(this.skuData.tableData[index]))
        })
      })
       this.$modal.confirm('确实要修改该商品SKU吗？').then(function () {
        return updateSku(updateSkuList);
      }).then(() => {
         this.getList()
         Object.assign(this._data.skuData, this.$options.data().skuData)
         this.isShowSku=false
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 获取商品品牌下拉框数据
    uniqueKeys(data) {
      const keysSet = new Set();
      data.forEach(item => {
        keysSet.add(item.key);
      });
      return Array.from(keysSet);
    },
    // 将数据转换为数组
    transformData(row) {
      const excludeKeys = ['promotionPrice', 'salePrice', 'stock', 'warningStock'];
      const result = [];
      for (const key in row) {
        if (row.hasOwnProperty(key) && !excludeKeys.includes(key)) {
          result.push({key, value: row[key]});
        }
      }
      return result;
    },
    // 将数据转换为对象
    deTransformData(data) {
      const result = {};
      for (const item of data) {
        result[item.key] = item.value;
      }
      return result;
    },
    //显示sku
    handleSku(row) {
      this.isShowSku = true
      Object.assign(this._data.skuData, this.$options.data().skuData)
      getSku(row.id).then(res => {
        if (res.code == 200) {
          this.skuSpDataList = JSON.parse(JSON.stringify(res.data))
          let defaultCol = [{label: '销售价格', prop: 'salePrice'},
            {label: '促销价格', prop: 'promotionPrice'},
            {label: '商品库存', prop: 'stock'},
            {label: '库存预警值', prop: 'warningStock'}]
          //转json
          let skuList = [];
          res.data.forEach(item => {
            skuList.push(...JSON.parse(item.spData))
          })
          let key = this.uniqueKeys(skuList)
          let newCol = key.map(item => {
            return {label: item, prop: item}
          })
          this.skuData.columns = [...newCol, ...defaultCol]
          //处理table数据
          res.data.forEach(item => {
            let obj = {
              salePrice: item.price,
              promotionPrice: item.promotionPrice,
              stock: item.stock,
              warningStock: item.warningStock
            }
            let skuAttr = this.deTransformData(JSON.parse(item.spData))
            //合并
            obj = {...obj, ...skuAttr}
            this.skuData.tableData.push(obj)
          })
        }
      })
    },
    handleUpdate(row) {
      this.$router.push({path: "/shopping/addPro", query: {id: row.id}})
    },
    /** 查询地区管理列表 */
    getBrandNames() {
      getBrandName().then(res => {
        this.brandList = res.data
      })
    },
    /** 查询品牌管理列表 */
    getRegionNames() {
      getRegionName().then(res => {
        this.regionList = res.data
      })
    },
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.serviceIds = this.serviceIdAll.join(',')
      // console.log(this.queryParams)
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        brandId: null,
        regionId: null,
        name: null,
        description: null,
        detailHtml: null,
        price: null,
        stockQuantity: null,
        defaultImg: null,
        albumPics: null,
        serviceIds: null,
        verifyStatus: null,
        promotionPrice: null,
        stock: null,
        lowStock: null,
        giftPoint: null,
        promotionType: null,
        status: null,
        isDelete: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品管理编号为"' + ids + '"的数据项？').then(function () {
        return delProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('shopping/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
    handleAdd() {
      this.$router.push('/shopping/addPro')
    },
    handleView(row) {
      this.$router.push({path: '/shopping/productDetail', query: {id: row.id}})
    }
  }
};
</script>
